import java.util.Arrays;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-11-08
 * Time: 19:08
 */



class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution15 {
    public long prev = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        return dfs(root);
    }

    public boolean dfs(TreeNode root) {
        if(root == null){
            return true;
        }
        boolean leftRet = dfs(root.left);
        //剪枝：如果左子树已经不满足，中间和右边都不需要判断了
        if(leftRet == false){
            return false;
        }
        boolean cur = false;
        if(root.val > prev){
            cur = true;
        }
        //剪枝：如果中间已经不满足，右边都不需要判断了
        if(cur == false){
            return false;
        }
        prev = root.val;
        boolean rightRet = dfs(root.right);
        return leftRet && cur && rightRet;
    }
}

class Solution5 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public static int sum = 0;

    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }
        if (low <= root.val && root.val <= high) {
            sum += root.val;
        }
        rangeSumBST(root.left, low, high);
        rangeSumBST(root.right, low, high);
        return sum;
    }

    public static void main(String[] args) {
        // 构建各个节点
        TreeNode root = new TreeNode(10);

        // 构建左子树（根为5）
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(3);
        root.left.left.left = new TreeNode(1);
        root.left.right = new TreeNode(7);
        root.left.right.left = new TreeNode(6);

        // 构建右子树（根为15）
        root.right = new TreeNode(15);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(18);
        int ret = new Solution5().rangeSumBST(root, 6, 10);
        System.out.println(ret);
    }



}